<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>WebSocket Chat</title>
    <style>
        body { font-family: Arial; padding: 20px; }
        #users { margin-bottom: 10px; }
        #chat-box { height: 300px; overflow-y: scroll; border: 1px solid #ccc; padding: 10px; }
        input, button { padding: 5px; margin-top: 5px; }
        .group { color: green; }
        .private { color: blue; }
    </style>
</head>
<body>
<h2>Chatroom</h2>

<div id="users"></div>

<div id="chat-box"></div>

<input type="text" id="toUser" placeholder="Recipient name" />
<br/>
<input type="text" id="message" placeholder="Enter message..." />
<button onclick="sendMessage('group')">Public Chat</button>
<button onclick="sendMessage('private')">Private Chat</button>

<script>
    // 获取用户名
    let username = prompt("Enter your name:");
    if (!username) {
        username = "Anonymous";
    }

    // 建立 WebSocket 连接
    const ws = new WebSocket('ws://localhost:8082/microblog/ws2/'+encodeURIComponent(username));

    // 更新在线用户列表
    function updateOnlineUsers(users) {
        const usersDiv = document.getElementById("users");
        usersDiv.innerHTML = "<strong>Online Users:</strong>";
        users.forEach(user => {
            if (user !== username) {
                console.log('hah')
                usersDiv.innerHTML += '<div>'+user+'</div>';
            }
        });
    }

    // 接收消息
    ws.onmessage = function(event) {
        // 使用原生 JSON.parse() 解析消息
        const data = JSON.parse(event.data);

        console.log(data)
        if (data.type === "online_users") {
            updateOnlineUsers(data.users);
        } else {
            const chatBox = document.getElementById("chat-box");
            const msgClass = data.type === "group" ? "group" : "private";
            const msg = '<div class="'+msgClass+'"><strong>'+data.from+ '":</strong>'+data.message+'"</div>';
            chatBox.innerHTML += msg;
            chatBox.scrollTop = chatBox.scrollHeight;
        }
    };

    // 发送消息
    function sendMessage(type) {
        const toUser = document.getElementById("toUser").value.trim();
        const message = document.getElementById("message").value.trim();
        if (message && ws.readyState === WebSocket.OPEN) {
            const json = {
                type: type,
                message: message
            };
            if (type === "private") {
                json.to = toUser;
            }
            // 使用原生 JSON.stringify() 发送消息
            ws.send(JSON.stringify(json));
            document.getElementById("message").value = "";
        }
    }
</script>
</body>
</html>